package repository;



import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class RepositoryImpl implements Repository {

	//Information requested via RMI.
	private Hashtable<Integer, ArrayList<ArrayList<Note>>> allMusic;
	private int sLength;
	private int instruments;
	
	//Parses xml file containing music.
	private FileParser handler;
	
	
	//Public methods.
	//Constructors
	public RepositoryImpl() throws RemoteException{
		super();
	}
	
	/**
	 * Takes in a filename and reads data from that file into the repository.
	 * @param filename File in which song data is stored.
	 */
	protected void readFile(String filename){
		read(filename);
		allMusic = handler.getMusicResults();
		sLength = handler.getSongLength();
		instruments = handler.getInstruments();
	}

	//RMI method implementations.
	public ArrayList<ArrayList<Note>> getMusic(int instrumentNum) throws RemoteException {
		return allMusic.get(instrumentNum);
	}

	public Integer getSongLength() throws RemoteException {
		return sLength;
	}	

	public Integer getNumInstruments() throws RemoteException {
		return instruments;
	}
	
	//Private methods.
	/**
	 * Reads in all info from a specified file.
	 * @param filename Name of an xml file complying with the required formatting.
	 * @return Hashtable containing the pieces of all instruments extracted from filename.
	 */
	private void read(String filename){
		
		handler = new FileParser();
		
		//Code as required to parse a given file.
		try{
			XMLReader parser = XMLReaderFactory.createXMLReader();	
			parser.setContentHandler(handler);
			parser.parse(filename);
		}
		catch(IOException e){
			System.out.println("Error reading URI: "+e.getMessage());
			System.exit(-1);
		}
		catch(SAXException e){
			System.out.println("Error parsing XML file: "+e.getMessage());
			System.exit(-1);
		}
		
	}

}
